package org.aplombh.java.utils.multiThread.create;

import lombok.Data;

import java.util.stream.IntStream;

/**
 * 实现Runnable接口
 * <p>
 * 实现接口Runnable具有多线程能力
 * 启动线程:传入目标对象+ Thread对象.start()
 * 推荐使用:避免单继承局限性，灵活方便，方便同一个对象被多个线程使用
 */
@Data
public class TestRunnable implements Runnable {
    private int ticketNumber = 10;

    @Override
    public void run() {
        while (ticketNumber > 0) {
            try {
                Thread.sleep(200L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " got the " + ticketNumber-- + "th ticket");
        }
    }

    public static void main(String[] args) {
        TestRunnable runnable = new TestRunnable();

        new Thread(runnable, "Ticket buyer 1").start();
        new Thread(runnable, "Ticket buyer 2").start();
        new Thread(runnable, "Ticket buyer 3").start();

    }
}

@Data
class TestRunnableRace implements Runnable {
    private int ticketNumber = 10;
    private static String winner;

    @Override
    public void run() {
        if (Thread.currentThread().getName().equals("rabbit")) {
            try {
                Thread.sleep(10L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        IntStream.rangeClosed(1, 100).forEach(i -> {
            if (gameOver(i)) return;
            System.out.println(Thread.currentThread().getName() + " ran " + i + " meters");
        });
    }

    public boolean gameOver(int steps) {
        if (winner != null)
            return true;
        if (steps == 100) {
            winner = Thread.currentThread().getName();
            System.out.println(winner + " ran " + 100 + " meters");
            System.out.println("winner is " + winner);
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        TestRunnableRace race = new TestRunnableRace();

        new Thread(race, "rabbit").start();
        new Thread(race, "turtle").start();

    }
}